#/bin/env python
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor, defer
from twisted.protocols import basic

import test_pb2


class ProxyProtocol(basic.LineReceiver):
    def connectionMade(self):
        proto_str = self.factory.proto_object.SerializeToString()
        to_send = proto_str + "\r\n"
        print len(proto_str)
        print len(to_send)
        self.transport.write(to_send) 

    def lineReceived(self, line):
        #protobuf parse
        #run factory deferred
        self.factory.deferred.callback(line)
        self.transport.loseConnection()

class ProxyClientFactory(ClientFactory):
    protocol = ProxyProtocol
    deferred = defer.Deferred()
    proto_object = None
    def startedConnecting(self, connector):
        print 'Started to connect.'

    def clientConnectionLost(self, connector, reason):
        #print 'Lost connection.  Reason:', reason
        pass

    def clientConnectionFailed(self, connector, reason):
        #print 'Connection failed. Reason:', reason
        pass

def connect():
    a = test_pb2.Book()
    a.book_name = "hhabook write by xiong123"
    a.author = "xiong123"
    factory = ProxyClientFactory()
    factory.proto_object = a
    reactor.connectTCP('127.0.0.1', 1079, factory)
    return factory.deferred

def done(result):
    print result
    return result

def main():
    d = connect()
    d.addCallback(done)
    d.addCallback(lambda _: reactor.stop())
    reactor.run()
    pass




if __name__ == "__main__":
    main()


# vim: st=2 sts=2 sw=2 noet

